import
  axios,
{
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig
} from 'axios';

// 定义接口
interface HttpResponse<T> {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: InternalAxiosRequestConfig;
  request?: any;
}

// 定义一个类，封装 axios
class HttpClient {
  private instance: AxiosInstance;

  constructor() {
    this.instance = axios.create({
      baseURL: import.meta.env.MODE === 'development' ? '/api' : 'https://bcqd.bingchenghb.com/api',
      timeout: 10000, // 超时时间，可以根据需要调整
      withCredentials: true, // 如果需要传递凭证，如Cookies
      headers: {
        'Accept': 'application/json', // 确保Accept头正确
        'Content-Type': 'application/json' // 设定Content-Type
      }
      // maxRedirects: 0 // 禁用重定向
    });

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
        // 可以在这里添加统一的请求头，比如 Authorization
        // config.headers['connection'] = 'keep-alive';
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        return response;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }

  public async get<T>(url: string, config?: AxiosRequestConfig): Promise<HttpResponse<T>> {
    const response = await this.instance.get<T>(url, config);
    return this.handleResponse<T>(response);
  }

  public async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<HttpResponse<T>> {
    const response = await this.instance.post<T>(url, data, config);
    return this.handleResponse<T>(response);
  }

  private handleResponse<T>(response: AxiosResponse<T>): HttpResponse<T> {
    return {
      data: response.data,
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
      config: response.config as InternalAxiosRequestConfig,
      request: response.request,
    };
  }
}

export default HttpClient;
